package network;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.channels.DatagramChannel;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

import model.Call;
import model.EnumCallStatus;

public class UDPReceiveAndRead extends Thread {
	private int bufferLength=640;
	private int portToListen;
	private AudioFormat format;
	private Call call;
	private boolean running;
	private DatagramSocket datagramSocket;
	private SourceDataLine lineHp;
	
	public UDPReceiveAndRead(int port, AudioFormat format, Call call){
		this.portToListen=port;
		this.format=format;
		this.call=call;
		running = true;
		System.out.println("[UDPReveiveAndRead] : Port = "+portToListen);
	}
	
	public void run(){
		try{

		byte[] buffer = new byte[bufferLength];
		DatagramPacket inPacket = null;
		datagramSocket = new DatagramSocket(portToListen);
		//datagramSocket.setReceiveBufferSize(bufferLength);
			DataLine.Info info2 = new 	DataLine.Info(SourceDataLine.class, format);
			lineHp = (SourceDataLine) AudioSystem.getLine(info2);
			lineHp.open(format);
			
			
			
			
			while (running){
				inPacket = new DatagramPacket(buffer, buffer.length);
				datagramSocket.receive(inPacket);
				if(call.getMuteSpeaker() == false && call.getStatus() == EnumCallStatus.ACTIV_ESTABLISHED) {
					lineHp.start();
					lineHp.write(buffer,0,buffer.length);
					lineHp.stop();
				}
			}
			System.out.println("[UDPReceive] Sortie de la boucle");
			lineHp.drain();
			lineHp.close();
		}	catch(InterruptedIOException ex) {
			System.out.println("Passage dans InterruptedIOException de UDPReveiveAndRead");
			 this.running=false;
			 lineHp.drain();
				lineHp.close();
		} catch (IOException e) {
			System.out.println("Passage dans IIOException de UDPReveiveAndRead");
			e.printStackTrace();
			 this.running=false;
			 lineHp.drain();
				lineHp.close();
		} catch (LineUnavailableException e) {
			System.out.println("Passage dans LineUnavailableException de UDPReveiveAndRead");
			e.printStackTrace();
			 this.running=false;
			 lineHp.drain();
				lineHp.close();
		}
	}

	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

	public DatagramSocket getDatagramSocket() {
		return datagramSocket;
	}

	public SourceDataLine getLineHp() {
		return lineHp;
	}
}
